import { FormItemRule } from 'naive-ui'
import _ from 'lodash'
import { App } from 'vue'

const required = (message: string, trigger = 'blur') => ({
  required: true,
  message,
  trigger
})

const number = (message: string, trigger = 'blur') => ({
  type: 'number',
  message,
  trigger
})

const min = (min: number, message: string, trigger = 'blur') => ({
  min,
  message,
  trigger
})

const email = (message: string, trigger = ['blur', 'change']) => ({
  type: 'email',
  message,
  trigger
})

const date = (message: string, trigger = 'blur') => ({
  type: 'date',
  message,
  trigger
})

const reg = (regex: RegExp, msg: string, trigger = 'blur') => {
  const validator = (rule: FormItemRule, value: string, callback) => {
    if (_.isArray(regex)) {
      _.forEach(regex, (item) => {
        if (item.test(value)) return callback(new Error(msg))
      })
    } else if (!regex.test(value)) return callback(new Error(msg))
    callback()
  }
  return { validator, trigger }
}

export const $rules = {
  required,
  number,
  min,
  email,
  date,
  reg
}

export default {
  install: (app: App) => (app.config.globalProperties.$rules = $rules)
}
